package com.yingjie.yingjieuser.controller;


import com.yingjie.commonbase.commons.JWTUtils;
import com.yingjie.commonbase.commons.ReturnObject;
import com.yingjie.commonbase.model.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yingjie.yingjieuser.service.UserService;
import org.springframework.web.bind.annotation.*;
import com.yingjie.commonsecurity.AuthUserContext;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {


    @Resource
    private UserService userService;

    @RequestMapping("/login")
    public Object login(@RequestBody Map<String,Object> params) throws JsonProcessingException {
        Object o = userService.wxLogin(params);
        Map retMap = new HashMap();
        if(o instanceof Map){
            Map map = new HashMap();
            map.put("openid",((Map) o).get("openid"));
            map.put("userId",((Map) o).get("userId"));
            retMap.put("token", JWTUtils.getToken(map));
        }else if(o instanceof User){
            Map map = new HashMap();
            map.put("openid",((User) o).getOpenid());
            map.put("userId",((User) o).getUserId());
            retMap.put("token",JWTUtils.getToken(map));
        }
        return ReturnObject.SUCCESS(retMap);
    }

    @PostMapping("/getUserInfo")
    public ReturnObject getUserInfo(){
        Integer userId = AuthUserContext.get().getUserId();
        User user = userService.getUserInfo(userId);
        if(user==null){
            return ReturnObject.ERROR("无此用户");
        }
        return ReturnObject.SUCCESS(user);
    }
}
